#!/usr/bin/env python3
"""
工业物联网数据采集系统启动脚本
检查环境并启动系统
"""

import sys
import os
import subprocess
import importlib
from pathlib import Path

def print_banner():
    """打印启动横幅"""
    print("🚀 工业物联网数据采集系统启动检查")
    print("=" * 50)

def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    print(f"✅ Python 版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major < 3 or (version.major == 3 and version.minor < 8):
        print("❌ Python版本过低，需要Python 3.8+")
        return False
    
    return True

def check_virtual_env():
    """检查虚拟环境"""
    venv_path = Path("iot-collector-env")
    in_venv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
    
    if not in_venv:
        print("⚠️  未检测到虚拟环境")
        print("建议在虚拟环境中运行")
        print_venv_guide()
        return False
    else:
        print("✅ 运行在虚拟环境中")
        return True

def check_dependencies():
    """检查依赖包"""
    print("\n🔍 检查依赖包...")
    
    # 核心依赖包
    core_deps = [
        ('flask', 'Flask'),
        ('yaml', 'PyYAML'),
        ('sqlite3', 'SQLite3'),
        ('requests', 'requests'),
        ('numpy', 'numpy'),
        ('pandas', 'pandas')
    ]
    
    # 工业协议依赖
    protocol_deps = [
        ('pymodbus', 'pymodbus'),
        ('paho.mqtt.client', 'paho-mqtt'),
        ('asyncua', 'asyncua'),
        ('snap7', 'python-snap7')
    ]
    
    missing_core = []
    missing_protocol = []
    
    # 检查核心依赖
    for module_name, package_name in core_deps:
        try:
            importlib.import_module(module_name)
            print(f"✅ {package_name}")
        except ImportError:
            missing_core.append(package_name)
            print(f"❌ {package_name} - 未安装")
    
    # 检查协议依赖
    for module_name, package_name in protocol_deps:
        try:
            importlib.import_module(module_name)
            print(f"✅ {package_name}")
        except ImportError:
            missing_protocol.append(package_name)
            print(f"⚠️  {package_name} - 未安装")
    
    if missing_core:
        print(f"\n❌ 缺少核心依赖: {', '.join(missing_core)}")
        return False, missing_core + missing_protocol
    elif missing_protocol:
        print(f"\n⚠️  缺少协议依赖: {', '.join(missing_protocol)}")
        print("系统可以启动，但部分协议功能不可用")
        return True, missing_protocol
    else:
        print("\n✅ 所有依赖包检查通过")
        return True, []

def install_dependencies(missing_deps):
    """安装缺失的依赖"""
    if not missing_deps:
        return True
    
    print(f"\n📦 安装缺失的依赖包: {', '.join(missing_deps)}")
    
    try:
        # 尝试自动安装
        cmd = [sys.executable, '-m', 'pip', 'install'] + missing_deps
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✅ 依赖包安装成功")
            return True
        else:
            print(f"❌ 依赖包安装失败: {result.stderr}")
            return False
    except Exception as e:
        print(f"❌ 安装过程出错: {e}")
        return False

def print_venv_guide():
    """打印虚拟环境设置指南"""
    print("\n📚 虚拟环境设置指南:")
    print("=" * 50)
    print("1. 创建虚拟环境:")
    print("   python -m venv iot-collector-env")
    print("2. 激活虚拟环境:")
    if os.name == 'nt':  # Windows
        print("   PowerShell: .\\iot-collector-env\\Scripts\\Activate.ps1")
        print("   CMD: iot-collector-env\\Scripts\\activate.bat")
    else:  # Linux/Mac
        print("   source iot-collector-env/bin/activate")
    print("3. 安装依赖:")
    print("   pip install --upgrade pip")
    print("   pip install -r requirements.txt")
    print("4. 运行系统:")
    print("   python 启动脚本.py")
    print("   或者: python main.py")
    print("💡 需要帮助请参考文档:")
    print("   - Python 3.12 环境配置指南: docs/Python3.12环境配置指南.md")
    print("   - 部署指南: docs/部署指南.md")
    print("   - README: README.md")

def check_config_files():
    """检查配置文件"""
    print("\n📄 检查配置文件...")
    
    config_files = [
        "config/config.yaml",
        "config/devices.json"
    ]
    
    missing_files = []
    for file_path in config_files:
        if Path(file_path).exists():
            print(f"✅ {file_path}")
        else:
            missing_files.append(file_path)
            print(f"❌ {file_path} - 文件不存在")
    
    if missing_files:
        print("\n⚠️  缺少配置文件，将使用默认配置")
        return False
    
    return True

def start_system():
    """启动系统"""
    print("\n🚀 启动工业物联网数据采集系统...")
    
    try:
        # 导入主模块
        sys.path.insert(0, str(Path(__file__).parent))
        
        # 启动主程序
        import main
        main.main()
        
    except ImportError as e:
        print(f"❌ 导入模块失败: {e}")
        print("请检查项目文件完整性")
        return False
    except Exception as e:
        print(f"❌ 系统启动失败: {e}")
        return False

def main():
    """主函数"""
    print_banner()
    
    # 1. 检查Python版本
    if not check_python_version():
        sys.exit(1)
    
    # 2. 检查虚拟环境
    in_venv = check_virtual_env()
    
    # 3. 检查依赖
    deps_ok, missing_deps = check_dependencies()
    
    if not deps_ok:
        print("\n❌ 缺少核心依赖，无法启动系统")
        print("\n🔧 解决方案:")
        print("1. 激活虚拟环境（如果未激活）")
        print("2. 运行: pip install -r requirements.txt")
        print("3. 重新启动系统")
        sys.exit(1)
    
    # 4. 尝试安装缺失的协议依赖
    if missing_deps:
        user_input = input(f"\n是否自动安装缺失的依赖包？({', '.join(missing_deps)}) [y/N]: ")
        if user_input.lower() in ['y', 'yes']:
            if install_dependencies(missing_deps):
                print("✅ 依赖安装完成，继续启动...")
            else:
                print("⚠️  部分依赖安装失败，系统仍可启动但功能受限")
    
    # 5. 检查配置文件
    check_config_files()
    
    # 6. 启动系统
    if start_system():
        print("\n✅ 系统启动成功！")
    else:
        print("\n❌ 系统启动失败！")
        sys.exit(1)

if __name__ == "__main__":
    main() 